package com.example.browser;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class prefix extends Activity {
    private ListView lv;
    private MyDatabaseHelper dbHelper;
    private String get_title,get_url;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private String titler, url;//按值查找详细信息
    int id; //按值查找id
    private ArrayList arrayList=new ArrayList();
    private boolean if_exsit;
    private EditText prefix,keyWord;
    private Button addprefix,cancel;
    SharedPreferences share;
    // SharedPreferences数据存储
    private static final String FILENAME="YX";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prefix);
        getWindow().setGravity(Gravity.CENTER);//底部出现

        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);//设置弹窗宽高
        lv=(ListView)findViewById(R.id.prefix_list);
        prefix=(EditText)findViewById(R.id.prefix);
        keyWord=(EditText)findViewById(R.id.keyWord);
        addprefix=(Button)findViewById(R.id.addprefix) ;
        cancel=(Button)findViewById(R.id.cancel) ;
        share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        if(share.getString("prefix","自动前缀【关闭】").equals("自动前缀【关闭】"))cancel.setText("已关闭");
        else cancel.setText("已开启");



        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();
        if(share.getString("jxvipsp", "首次打开").equals("首次打开")){
            insert();
            edit.putString("jxvipsp", "早已打开");
            edit.commit();
        }
        intview();
        queryinfo();

        //点击函数：
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exsit) {
                    delete_dialog(position);
                }


            }
        });
    }
    public void insert() {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql1 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://okjx.cc/?url=" + "','" + "m.v.qq.com/x/m/play" + "')";
        String sql2 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://okjx.cc/?url=" + "','" + "youku.com/alipay_video/" + "')";
        String sql3 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://okjx.cc/?url=" + "','" + "youku.com/video/" + "')";
        String sql4 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://okjx.cc/?url=" + "','" + "youku.com/v_show/" + "')";
        String sql5 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://okjx.cc/?url=" + "','" + "iqiyi.com/v_" + "')";
        String sql6 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://z1.m1907.cn/?jx=" + "','" + "m.bilibili.com/bangumi/play/" + "')";
        String sql7 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://17kyun.com/api.php?url=" + "','" + "sohu.com/(.-)aid=" + "')";
        String sql8 = "insert into " + "addprefixDB" + "(prefix,keyword) values('"
                + "https://jx.m3u8.tv/jiexi/?url=" + "','" + "mgtv.com/b/" + "')";

        db.execSQL	(sql1);
        db.execSQL	(sql2);
        db.execSQL	(sql3);
        db.execSQL	(sql4);
        db.execSQL	(sql5);
        db.execSQL	(sql6);
        db.execSQL	(sql7);
        db.execSQL	(sql8);
        db.close();
    }
    private void intview() {
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();

        addprefix.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!prefix.getText().toString().equals("")&&!keyWord.getText().toString().equals("")){
                    selectprefix(prefix.getText().toString(),keyWord.getText().toString());
                }else {
                    Toast.makeText(prefix.this,"不能留有空白",Toast.LENGTH_SHORT).show();
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper = new MyDatabaseHelper(com.example.browser.prefix.this,"dmbrowser.db",null,1);
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
                //查询语句也可以这样写
                Cursor cursor = db.query("addprefixDB", null, null, null, null, null, "id desc");
                if (cursor != null && cursor.getCount() > 0) {
                    if(share.getString("prefix","自动前缀【关闭】").equals("自动前缀【关闭】")){
                        cancel.setText("已开启");
                        edit.putString("prefix","自动前缀【开启】");
                        edit.commit();
                        Toast.makeText(prefix.this, "已开启", Toast.LENGTH_SHORT).show();
                    }else if (share.getString("prefix","自动前缀【关闭】").equals("自动前缀【开启】")){
                        cancel.setText("已关闭");
                        edit.putString("prefix","自动前缀【关闭】");
                        edit.commit();
                        Toast.makeText(prefix.this, "已关闭", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(prefix.this, "请先添加", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }

    public void delete_dialog(int position){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete(position);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //bookmarkDB删除函数：
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("addprefixDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        queryinfo();
    }


    //查询数据库里的字段
    public void selectprefix(String prefix,String keyword) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
        //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
        String sql ="SELECT * FROM addprefixDB WHERE keyword='"+keyword+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {
            //https://codingdict.com/questions/117721
            //Toast.makeText(WebView.this,result.getString(1), Toast.LENGTH_SHORT).show();
            Toast.makeText(prefix.this, result.getString(1)+"已存在", Toast.LENGTH_LONG)
                    .show();
            result.close();
            db.close();

        }
        else {
            addprefix(prefix,keyword);
            result.close();
            db.close();

        }


    }
    //文件夹表添加数据
    public void addprefix(String prefix,String keyword) {
        //第二个参数是数据库名
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(prefix.this, "dmbrowser.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("prefix", prefix);
        values.put("keyword", keyword);
        //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
        db.insert("addprefixDB", null, values);
        Toast.makeText(prefix. this, "添加成功", Toast.LENGTH_SHORT).show();
        arrayList.clear();
        queryinfo();
        //刷新UI
    }

    public void queryinfo(){
        arrayList.clear();
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query("addprefixDB", null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exsit=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("prefix", get_title);
                map.put("keyword", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"prefix","keyword"},
                        new int[] {R.id.title,R.id.url});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exsit=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("prefix", "暂时没有添加网络前缀");
            map.put("keyword", "此处是存放你要识别的关键词");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"prefix","keyword"},
                    new int[] {R.id.title,R.id.url});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();//点击窗口外部区域 弹窗消失
        return true;
    }
}